using System;
using System.Collections.Generic;
using System.Linq;

namespace HtmlUtilities.UITest
{
    public static class DocumentCommands
    {
        public static IEnumerable<Command<string>> GetCommands()
        {
            Html.Page.Document.DocumentReady += Document_DocumentReady;

            return new List<Command<string>>
                       {
                           new Command<string>("Body", () => Html.Page.Document.Body.TagName),
                           new Command<string>("Cookies", () => Html.Page.Document.Cookies),
                           new Command<string>("DocumentElement", () => Html.Page.Document.DocumentElement.TagName),
                           new Command<string>("DocumentUri", () => Html.Page.Document.DocumentUri.ToString()),
                           new Command<string>("IsReady", () => Html.Page.Document.IsReady.ToString()),
                           new Command<string>("QueryString", () => Html.Page.Document.QueryString.QueryJoin()),
                           new Command<string>("CreateElement", CreateElementTest),
                           new Command<string>("GetElementsByTagName", GetElementsByTagNameTest),
                           new Command<string>("Submit", () => { Html.Page.Document.Submit(); return "Submitting";}),
                           new Command<string>("Submit('myForm')", SubmitMyForm)
                       };
        }

        static void Document_DocumentReady(object sender, EventArgs e)
        {
            TestDiv.SetProperty("innerHTML", "Ready To Test");
        }

        private static IHtmlElement TestDiv { get { return Html.Page.Document.GetElementById("testing"); } }

        private static string SubmitMyForm()
        {
            var form = Html.Page.Document.CreateElement("form");
            form.Id = "MyForm";
            form.SetAttribute("method", "get");
            TestDiv.AppendChild(form);

            var input = Html.Page.Document.CreateElement("input");
            input.Id = "MyInput";
            input.SetAttribute("name", "MyInput");
            input.SetAttribute("type", "text");
            input.SetProperty("value", "Woot");
            form.AppendChild(input);

            Html.Page.Document.Submit("MyForm");

            return "Submitting...";
        }

        private static string GetElementsByTagNameTest()
        {
            var tags = Html.Page.Document.GetElementsByTagName("div");
            return "DIV ids: " + string.Join(", ", tags.Select(tag => (tag as IHtmlElement).Id).ToArray());
        }

        private static string CreateElementTest()
        {
            var link = Html.Page.Document.CreateElement("a");
            link.SetProperty("innerHTML", "Cnn");
            link.SetAttribute("href", "http://cnn.com");
            TestDiv.AppendChild(link);
            return "Expect a CNN link";
        }
    }
}